package com.jet.core.utils;

import cn.hutool.core.util.StrUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class StockUtil {
    public static final Long BASE_UNIT = 1000L;
    public static final int BASE_SCALE = 3;
    public static final RoundingMode ROUNDING_MODE = RoundingMode.HALF_UP;

    /**
     * BigDecimal转logn
     *
     * @param amount
     * @return
     */
    public static long parse(BigDecimal amount) {
        if (amount == null) {
            return 0;
        }
        return amount.multiply(BigDecimal.valueOf(BASE_UNIT)).longValue();
    }

    /**
     * 字符串金额转long
     *
     * @param amount
     * @return
     */
    public static long parse(String amount) {
        if (StrUtil.isBlank(amount)) {
            return 0;
        }
        return parse(parseBigDecimal(amount));
    }

    /**
     * long 转 BigDecimal
     *
     * @param amount
     * @return
     */
    public static BigDecimal parseBigDecimal(long amount) {
        return parseBigDecimal(amount, BASE_SCALE);
    }

    /**
     * long 转指定小数位数的BigDecimal
     *
     * @param amount
     * @param scale
     * @return
     */
    public static BigDecimal parseBigDecimal(long amount, int scale) {
        return BigDecimal.valueOf(amount).divide(BigDecimal.valueOf(BASE_UNIT), scale, ROUNDING_MODE);
    }

    /**
     * BigDecimal数值格式化成默认小数位
     *
     * @param amount
     * @return
     */
    public static BigDecimal format(BigDecimal amount) {
        return format(amount, BASE_SCALE);
    }

    /**
     * BigDecimal 格式化小数位
     *
     * @param amount
     * @param scale
     * @return
     */
    public static BigDecimal format(BigDecimal amount, int scale) {
        return amount.setScale(scale, ROUNDING_MODE);
    }

    /**
     * 字符串数值格式化小数位
     *
     * @param amount
     * @return
     */
    public static BigDecimal parseBigDecimal(String amount) {
        if (StrUtil.isBlank(amount)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(Double.parseDouble(amount)).multiply(BigDecimal.valueOf(BASE_UNIT)).setScale(BASE_SCALE, ROUNDING_MODE);
    }
}
